function createGrid(url, title, region, reader, cm, sm) {
    var grid = new Ext.grid.GridPanel({
        ds: new Ext.data.Store({
			url: url,
            reader: reader
        }),
		region: region,
        cm: cm,
        sm: sm,
        width:600,
        height:300,
        title: title,
        iconCls:'icon-grid',
		split: true,
		width: 350,
		frame: true
    });
	return grid;
}

function processAssocResponse(xml) {
	if(xml.status != 201) {
		Ext.MessageBox.alert('Error', 'Las asociaciones no pudieron agregarse');
	} else {
		alert(xml.getResponseHeader('Location'));
		Ext.MessageBox.alert('Mensaje', 'Las asociaciones han sido creadas');
	}
}

function createAssociationsCRPR(gridCR, gridPR, container) {
	var m = gridCR.getSelections();
	var m2 = gridPR.getSelections();
	if (m.length > 0 && m2.length > 0) {
		var xmlDocument = '<?xml version="1.0" encoding="UTF-8" ?>';
		xmlDocument += '<associations>';
		for(i=0; i < m.length; i++) {			
			for(j=0; j < m2.length; j++) {
				xmlDocument += '<association>';
				xmlDocument += '<resource type="cr">';
				xmlDocument += '<id>' + m[i].id + '</id>';
				xmlDocument += '</resource>';
				xmlDocument += '<resource type="pr">';
				xmlDocument += '<id>' + m2[j].id + '</id>';
				xmlDocument += '</resource>';
				xmlDocument += '</association>';
			}
		}		
		xmlDocument += '</associations>';
		alert(xmlDocument);
		var url_assoc_cr_pr = getProjectName() + '/associations/crpr';
		$.ajax({
			type: "post",
			url: url_assoc_cr_pr,
			dataType: "xml",
			async: false,
			data: {xml: xmlDocument},
			complete: function(xml) {processAssocResponse(xml);}
		});
		container.close();
	} else {
		Ext.MessageBox.alert('Mensaje', 'Por favor, seleccione al menos un requerimiento de cada tipo');
	}
}

var agregarAssocCRPR = function() {
	var projectName = getProjectName();
	
	var smAssocCR = new Ext.grid.CheckboxSelectionModel();
	var smAssocPR = new Ext.grid.CheckboxSelectionModel();

	var readerAssocCR = new Ext.data.XmlReader({ record: 'requirement', id: 'id'}, [ 'name']);
	var cmAssocCR = new Ext.grid.ColumnModel([
			smAssocCR,
			{header: "Nombre", width: 280, dataIndex: 'name', editor: new Ext.form.TextField({allowBlank: false})}
	]);
    cmAssocCR.defaultSortable = true;
	
	var gridAssocCR = createGrid(projectName + '/clientrequirements', 'Requerimientos de Cliente', 'center', readerAssocCR, cmAssocCR, smAssocCR);	
	
	var readerAssocPR = new Ext.data.XmlReader({record: 'requirement', id: 'id'}, ['name']);
	var cmAssocPR = new Ext.grid.ColumnModel([
			smAssocPR,
			{header: "Nombre", width: 280, dataIndex: 'name', editor: new Ext.form.TextField({allowBlank: false})}
	]);
    cmAssocPR.defaultSortable = true;	
	
	var gridAssocPR = createGrid(projectName + '/productrequirements', 'Requerimientos de Sistema', 'east', readerAssocPR, cmAssocPR, smAssocPR);

    var win = new Ext.Window({
        width: 700,
        height: 500,
        minWidth: 300,
        minHeight: 250,
        layout: 'border',
        plain:true,
		modal: true,
        bodyStyle:'padding:5px;',
		title: 'Asociar Requerimiento de Cliente con Requerimiento de Productos',
        buttonAlign:'center',
        items: [gridAssocCR, gridAssocPR, {region:'north', html:'Seleccione los requerimientos que desea asociar', frame: true}],
		buttons: [{
                    text:'Asociar',
                    handler: function() {createAssociationsCRPR(gridAssocCR, gridAssocPR, win);}
                },{
                    text: 'Cerrar',
                    handler: function(){
                        win.close();
                    }
                }]
    });
	gridAssocCR.store.load();
	gridAssocPR.store.load();
    win.show();	
};